package com.danicsoft.daide.command;

import com.danicsoft.daide.token.TokenGroup;
import com.danicsoft.daide.token.TokenMap.Commands;

/**
 * Implements the MIS command. From Eric Wald's <a
 * href="http://pydip.brainshell.org/docs/syntax.html">protocol specification</a>,
 * v0.14:
 * <h4><a name="HST">client_request = HST</a> (turn)</h4>
 * <p>
 * Any previous turn's results may be requested by sending the <b>HST</b>
 * command to the server with the turn as a parameter (for example, <b>HST (SPR
 * 1901)</b> ). The server will reply by sending the <b>ORD</b> messages for
 * that phase, followed by <b>SCO</b> and <b>NOW</b> messages to give the
 * position after the turn requested. <b>SCO</b> will be sent after every
 * <b>HST</b> command, not just those where supply centre ownership changes.
 * <b>REJ (HST (turn))</b> is sent if the requested turn doesn't exist.
 * </p>
 * 
 * @author Daniel Yule (daniel.yule@gmail.com)
 * @version 1.0
 */
public class HistoryCommand extends QueryableCommand {

	/**
	 * The turn we are requesting the history for. If null, then for the first
	 * turn.
	 */
	private Turn turnFor = new Turn();

	/**
	 * Constructs a new <code>HistoryCommand</code> from the parameters given.
	 * 
	 * @param tokens
	 *        The tokens to load this command from. Should consist of a
	 *        TokenGroup with a year and a season.
	 * @throws ParseException
	 *         If there was a problem reading from the tokens.
	 */
	public HistoryCommand(TokenGroup tokens) throws ParseException {
		super(tokens);
	}

	/**
	 * Consutrct a new HistoryCommand to send to the server as a query. This
	 * doesn't yet do anything, but it will soon.
	 */
	public HistoryCommand() {}

	/**
	 * Construct a new HistoryCommand to send to the server to request the
	 * history for the given turn.
	 * 
	 * @param turn
	 *        The turn to request history for.
	 */
	public HistoryCommand(Turn turn) {
		turnFor = turn.clone();
	}

	@Override
	public byte getType() {
		return Commands.HST;
	}

	@Override
	public String toString() {
		return "History for " + (isQuery() ? "the first turn." : turnFor.toString());
	}

	@Override
	protected void doNonQueryIO(TokenIO tokenIO, TokenGroup tokens) throws ParseException {
		turnFor.doIO(tokenIO, tokens);

	}

	/**
	 * Gets the turn that we are requesting the history for.
	 * 
	 * @return The turn we are requesting or null if we are requesting the first
	 *         turn.
	 */
	public Turn getTurn() {
		return isQuery() ? null : turnFor;
	}

}
